local numKey = KEYS[1]
local countKey = KEYS[2]
local type = KEYS[3]
local time = KEYS[4]

local tmpNum=redis.call('get', numKey)
local tmpCountKey=redis.call('get', countKey)

if not tmpNum or tonumber(tmpNum) < 0 then
    return nil
end

if not tmpCountKey or tonumber(tmpCountKey) < 0 then
    return nil
end

local currentNum = tonumber(tmpNum)
local currentCount = tonumber(tmpCountKey)

if currentNum <= 0 then
    return tostring(-1)
end

if currentNum == 1 then
    redis.call('decr', numKey)
    redis.call('decrby', countKey, currentCount)
    return tostring(currentCount + 1) .. ',' .. tostring(currentCount - currentCount) .. "," .. tostring(currentNum - 1)
end

if type == '1' then
    local result = math.floor(currentCount / currentNum);
    redis.call('decr', numKey)
    redis.call('decrby', countKey, result)
    return tostring(result + 1) .. ',' .. tostring((currentCount - result) + 1) .. "," .. tostring(currentNum - 1)
end

if type == '2' then
    local maxRandom = 2 * (currentCount / currentNum)

    math.randomseed(tonumber(time))

    local randomValue = math.random(0, maxRandom)
    if currentCount < randomValue then
        return tostring(-2)
    end
    redis.call('decr', numKey)
    redis.call('decrby', countKey, randomValue)
    return tostring(randomValue + 1) .. ',' .. tostring((currentCount - randomValue) + 1) .. "," .. tostring(currentNum - 1)
end